package bby.app.fettool;

import java.io.*;
import java.net.Socket;

public class Cilent  {
    int port=8888;
    String host="localhost";
    SenderPage senderPage;
    public Cilent(String host, int port, SenderPage senderPage) {
        this.port=port;
        this.host=host;
        this.senderPage=senderPage;
    }

    void setPort(int port){
        this.port=port;
    }
    Cilent(String host,int port){
        this.port=port;
        this.host=host;
    }
    public String downloadPubKey() throws IOException {
        Socket socket = new Socket(host, port);
        DataOutputStream output = new DataOutputStream(socket.getOutputStream());
        DataInputStream input = new DataInputStream(socket.getInputStream());

        output.writeUTF("GETKEY");//请求获取公钥
        output.flush();
        String pubKey=input.readUTF();//获取公钥
        output.close();
        input.close();
        socket.close();
        return pubKey;
    }
    private void print(String msg){
        senderPage.print(msg);
    }
    public void sendFile(File file,String md5,String key) {
        try {
            print("连接到 " + host + " on port " + port);
            Socket socket = new Socket(host, port);

            print("连接成功！");
            DataOutputStream output = new DataOutputStream(socket.getOutputStream());
            DataInputStream input = new DataInputStream(socket.getInputStream());
            output.writeUTF("SEND");

            print("发送文件名...");
            output.writeUTF(file.getName());//发送文件名
            output.flush();
            print("发送秘钥...");

            output.writeUTF(key);//发送秘钥
            output.flush();
            print("发送MD5...");
            output.writeUTF(md5);//发送MD5
            output.flush();

            print("发送文件...");
            InputStream ins = new BufferedInputStream(new FileInputStream(file));
//            output.writeLong(file.length());//发送文件大小
//            output.flush();

            byte[] buffer = new byte[1024];
            int bytes=0;
            double cnt=0;
            double len=file.length()/1024;

            while ((bytes=ins.read(buffer))>0){//发文件
                output.write(buffer,0,bytes);
                output.flush();

                if (++cnt%1024==0)
                    print("已上传："+(int)(cnt*100/len)+"%");
            }
            print("上传完毕，等待对方验证！");
//            output.write(buffer,0,0);//完成标记
//            output.flush();
            String res=input.readUTF();
            if ("OK".equals(res))
                print("发送成功！");
            else print("MD5验证失败，文件可能被劫持，或者有损！");
            input.close();
            output.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
